package com.linghui.videoplus.ipai.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Random;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

/**
 * @类说明：
 * @author : Bcker
 * @weibo : http://weibo.com/bcker
 * @version 创建时间：2011-8-2 下午4:43:56
 * @授权
 */
public class SinaTokenUtils {
//	public static String oauth_callback = "lkapp://uploadActivity";
	public static String appKey = "726832296";
	public static String appSecret = "f187c0a4a06156801378d45e20ba1ca6"; // 请正确填写，不然会影响到授权的正常进行

	/*
	 * 
	 * 用于获取RequestToken，也就是授权的第一步，如果还不太懂得步骤的请查看 http://open.weibo.com/wiki/Oauth
	 * 此方法在实际开发中强烈建议不要写成静态函数···因为一般不常调用···
	 */
	public static String getRequestToken(String oauth_callback) {
		HttpURLConnection con = null;
		Random RAND = new Random();
		// a b c d e f g h i j k l m n o p q r s t u v w x y z
		// 参数生成的baseString 中的参数是经过字母排序的，如果参数名一样，那么值进行二次排序。
		String method = "POST";
		String url = "http://api.t.sina.com.cn/oauth/request_token";

		String oauth_consumer_key = appKey;
		long oauth_nonce;
		String oauth_signature_method = "HMAC-SHA1";
		long oauth_timestamp;
		String oauth_version = "1.0";

		oauth_timestamp = System.currentTimeMillis() / 1000;
		oauth_nonce = oauth_timestamp + RAND.nextInt();
		String tempcallbackurl = oauth_callback;
		try {
			tempcallbackurl = URLEncoder.encode(tempcallbackurl, "UTF-8");
		} catch (UnsupportedEncodingException e3) {
			e3.printStackTrace();
		}
		// 生成baseString，一定要注意baseString总个元素的顺序（顺序是按照参数名字母来排序的，如果参数名相同则安装参数），和是否经过了encode处理和处理具体步骤。
		// 其中凡事url类型的都要先encode再放到baseString里面，然后再对所有的参数组成的String进行一次encode，
		// 最后在前面加上访问方式和encode过的地址,

		String baseString = "oauth_callback=" + tempcallbackurl
				+ "&oauth_consumer_key=" + oauth_consumer_key + "&oauth_nonce="
				+ oauth_nonce + "&oauth_signature_method="
				+ oauth_signature_method + "&oauth_timestamp="
				+ oauth_timestamp + "&oauth_version=" + oauth_version;
		String tempStr = null;
		try {
			baseString = URLEncoder.encode(baseString, "UTF-8");
			tempStr = URLEncoder.encode(url, "UTF-8");
		} catch (UnsupportedEncodingException e2) {
			e2.printStackTrace();
		}
		baseString = method + '&' + tempStr + "&" + baseString;
		byte[] byteHMAC = null;
		String oauth_signature = null;
		/*
		 * 生成oauth_signature
		 */
		Mac mac = null;
		try {
			mac = Mac.getInstance("HmacSHA1");

			// 注意个授权的过程所要用到的key都不一样，而且记得先encode在组合起来
			String key = URLEncoder.encode(appSecret, "UTF-8") + "&";
			SecretKeySpec spec = new SecretKeySpec(key.getBytes(), "HmacSHA1");
			mac.init(spec);
			byteHMAC = mac.doFinal(baseString.getBytes());
//			oauth_signature = new BASE64Encoder().encode(byteHMAC);
			oauth_signature = Base64.encode(byteHMAC);
			oauth_signature = URLEncoder.encode(oauth_signature, "UTF-8");
		} catch (Exception e1) {
			oauth_signature = "error";
			e1.printStackTrace();
		}
		// httpHeader的数据无顺序问题，但参数一点要和basestring中的完全一样，不能多也不能少，更不能改变。
		String httpHeaderStr = "OAuth oauth_consumer_key=\""
				+ oauth_consumer_key + "\",oauth_signature_method=\""
				+ oauth_signature_method + "\",oauth_timestamp=\""
				+ oauth_timestamp + "\",oauth_nonce=\"" + oauth_nonce
				+ "\",oauth_version=\"" + oauth_version
				+ "\",oauth_signature=\"" + oauth_signature
				+ "\",oauth_callback=\"" + oauth_callback + "\"";

		// 打开连接
		try {
			URL postUrl = new URL(url);
			con = (HttpURLConnection) postUrl.openConnection();
			// 设置各种超时
			con.setConnectTimeout(20000);
			con.setReadTimeout(120000);
			con.setDoInput(true);
			// 注意Authorization不能错
			con.addRequestProperty("Authorization", httpHeaderStr);
			// 此处的访问方式要和baseString里面的保持一致才行；
			con.setRequestMethod("POST");
			// 获取返回代码
			int code = con.getResponseCode();
			InputStream is = con.getInputStream();
			BufferedReader br = new BufferedReader(new InputStreamReader(is,
					"UTF-8"));
			StringBuffer buf = new StringBuffer();
			String line;
			while (null != (line = br.readLine())) {
				buf.append(line).append("\n");
			}
			System.out.println(buf);
			return buf.toString();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "error";

	}

	/*
	 * 
	 * 用于获取AcsessToken，也就是授权的最后一步，和前面一个方法大同小异，我就不再多解析了···
	 */
	public static String getAcsessToken(String oauthtoken,
			String oauthTokenSecret, String oauthverifier) {

		HttpURLConnection con = null;
		Random RAND = new Random();
		// a b c d e f g h i j k l m n o p q r s t u v w x y z
		// 参数生成的baseString 中的参数是经过字母排序的，如果参数名一样，那么值进行二次排序。
		String consumerSecret = appSecret;
		String method = "POST";
		String url = "http://api.t.sina.com.cn/oauth/access_token";
		String oauth_consumer_key = appKey;
		long oauth_nonce;
		String oauth_signature_method = "HMAC-SHA1";
		long oauth_timestamp;
		String oauth_token = oauthtoken;
		String oauth_verifier = oauthverifier;
		String oauth_version = "1.0";

		oauth_timestamp = System.currentTimeMillis() / 1000;
		oauth_nonce = oauth_timestamp + RAND.nextInt();

		String baseString = "oauth_consumer_key=" + oauth_consumer_key
				+ "&oauth_nonce=" + oauth_nonce + "&oauth_signature_method="
				+ oauth_signature_method + "&oauth_timestamp="
				+ oauth_timestamp + "&oauth_token=" + oauth_token
				+ "&oauth_verifier=" + oauth_verifier + "&oauth_version="
				+ oauth_version;
		String tempStr = null;
		try {
			baseString = URLEncoder.encode(baseString, "UTF-8");
			tempStr = URLEncoder.encode(url, "UTF-8");
		} catch (UnsupportedEncodingException e2) {
			e2.printStackTrace();
		}
		baseString = method + '&' + tempStr + "&" + baseString;
		byte[] byteHMAC = null;
		String oauth_signature = null;
		/*
		 * 生成oauth_signature
		 */
		Mac mac = null;
		try {
			mac = Mac.getInstance("HmacSHA1");
			String key = URLEncoder.encode(consumerSecret, "UTF-8") + "&"
					+ URLEncoder.encode(oauthTokenSecret, "UTF-8");
			SecretKeySpec spec = new SecretKeySpec(key.getBytes(), "HmacSHA1");
			mac.init(spec);
			byteHMAC = mac.doFinal(baseString.getBytes());
			oauth_signature = Base64.encode(byteHMAC);
			oauth_signature = URLEncoder.encode(oauth_signature, "UTF-8");
		} catch (Exception e1) {
			oauth_signature = "error";
			e1.printStackTrace();
		}
		String httpHeaderStr = "OAuth oauth_consumer_key=\""
				+ oauth_consumer_key + "\",oauth_signature_method=\""
				+ oauth_signature_method + "\",oauth_timestamp=\""
				+ oauth_timestamp + "\",oauth_nonce=\"" + oauth_nonce
				+ "\",oauth_version=\"" + oauth_version
				+ "\",oauth_signature=\"" + oauth_signature
				+ "\",oauth_token=\"" + oauth_token + "\",oauth_verifier=\""
				+ oauth_verifier + "\"";

		// 打开连接
		try {
			URL postUrl = new URL(url);
			con = (HttpURLConnection) postUrl.openConnection();
			con.setConnectTimeout(20000);
			con.setReadTimeout(120000);
			con.setDoInput(true);
			con.addRequestProperty("Authorization", httpHeaderStr);
			con.setRequestMethod("POST");
			int code = con.getResponseCode();
			InputStream is = con.getInputStream();
			BufferedReader br = new BufferedReader(new InputStreamReader(is,
					"UTF-8"));
			StringBuffer buf = new StringBuffer();
			String line;
			while (null != (line = br.readLine())) {
				buf.append(line).append("\n");
			}
			System.out.println(buf);
			return buf.toString();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "error";

	}

}
